package ar.com.ironsoft.javaopenauth.web.servlets.hotmail;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.com.ironsoft.javaopenauth.dto.OAuthToken;
import ar.com.ironsoft.javaopenauth.url.URLService;
import ar.com.ironsoft.javaopenauth.utils.HttpMethod;

@SuppressWarnings("serial")
public class ContactsServlet extends HttpServlet{

	private static final Logger log = Logger.getLogger(ContactsServlet.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		doPost(request,response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		Map<String,String> headers = new HashMap();
		
		OAuthToken token = (OAuthToken)request.getSession().getAttribute("oauth_token");
		
		headers.put("Authorization", "WRAP access_token="+(token).getAccessToken());
		
		URLService urlService = new URLService();
		String json = urlService.fetchJsonUrl("http://apis.live.net/V4.1/cid-"+token.getUserId()+"/Contacts/AllContacts", HttpMethod.GET, null,headers);
		
		request.setAttribute("json", json);
		
		try{
			request.getRequestDispatcher("/contacts.jsp").forward(request, response);
		}catch(ServletException e){
			log.log(Level.WARNING, "server error when redirecting to contacts.jsp",e);
			response.getWriter().println("Some server error ocurred. " + e.getMessage());
		}
	}
}
